<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="教练姓名" prop="coachName">
        <el-input
          v-model="queryParams.coachName"
          placeholder="请输入教练姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="教练手机号" label-width="82" prop="coachMobile">
        <el-input
          v-model="queryParams.coachMobile"
          placeholder="请输入教练手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="授权服务" prop="serviceIds">
        <el-cascader
          class="w-100%"
          clearable
          v-model="queryParams.serviceIds"
          :options="serviceClassTree"
          :props="{ label: 'name', value: 'id' }"
          filterable/>
      </el-form-item>
      <el-form-item label="上课雪场" prop="venueId">
        <el-select
          v-model="queryParams.venueId"
          placeholder="请选择上课雪场"
          clearable
          class="!w-240px">
          <el-option
            v-for="item in venues"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户手机号" label-width="82" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入用户手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker
          v-model="queryParams.orderTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="支付时间" prop="paymentTime">
        <el-date-picker
          v-model="queryParams.paymentTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="请选择支付状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待支付" :value="0" />
          <el-option label="已支付" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="取消状态" prop="cancelType">
        <el-select
          v-model="queryParams.cancelType"
          placeholder="请选择取消状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未取消" :value="0" />
          <el-option label="系统取消" :value="1" />
          <el-option label="用户取消" :value="2" />
          <el-option label="教练取消" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待接单" :value="0" />
          <el-option label="已取消" :value="1" />
          <el-option label="待上课" :value="2" />
          <el-option label="待确认" :value="3" />
          <el-option label="已完成" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="退款状态" prop="refundStatus">
        <el-select
          v-model="queryParams.refundStatus"
          placeholder="请选择退款状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未退款" :value="0" />
          <el-option label="退款中" :value="1" />
          <el-option label="已到账" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
<!--        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['business:order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['business:order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>-->
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['business:order:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="订单编号" min-width="200" align="center" prop="orderNo" />
      <el-table-column label="用户信息" min-width="200" align="left" prop="userId">
        <template #default="{ row }">
          {{ row.nickname }} ({{row.mobile}})
        </template>
      </el-table-column>
      <el-table-column label="教练信息" min-width="200" align="left" prop="coachId">
        <template #default="{ row }">
          <p v-if="row.coachName && row.coachMobile">{{ row.coachName }} ({{row.coachMobile}})</p>
          <el-tag type="warning" v-else>未分配教练</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上课信息" align="left" min-width="210" prop="attendClassDate">
        <template #default="{ row }">
          <p>时间：{{ row.attendClassDate }} - {{ row.startTime }}</p>
          <p>地点：{{ row.venueName }}</p>
          <p>课程：{{ row.serviceName }}</p>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="paymentAmount">
        <template #default="{ row }">
          <p>￥ {{ row.paymentAmount / 100 }}</p>
        </template>
      </el-table-column>
      <el-table-column
        label="下单时间"
        align="center"
        prop="orderTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="订单状态" align="center" min-width="82" prop="status">
        <template #default="{ row }">
          <el-tag type="warning" v-if="row.status === 0">待接单</el-tag>
          <el-tag type="info" v-else-if="row.status === 1">已取消</el-tag>
          <el-tag type="danger" v-else-if="row.status === 2">待上课</el-tag>
          <el-tag v-else-if="row.status === 3">待确认</el-tag>
          <el-tag type="success" v-else>已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" min-width="82" prop="paymentStatus">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.paymentStatus">已支付</el-tag>
          <el-tag type="info" v-else>待支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="退款状态" align="center" min-width="82" prop="refundStatus">
        <template #default="{ row }">
          <el-tag type="info" v-if="row.refundStatus === 0">未退款</el-tag>
          <el-tag type="danger" v-else-if="row.refundStatus === 1">退款中</el-tag>
          <el-tag type="success" v-else>已到账</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="支付时间"
        align="center"
        prop="paymentTime"
        :formatter="dateFormatter"
        width="180px"
      />
<!--      <el-table-column
        label="接单时间"
        align="center"
        prop="receivedTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="取消时间"
        align="center"
        prop="cancelTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="上课时间"
        align="center"
        prop="attendClassTime"
        :formatter="dateFormatter"
        width="180px"
      />-->
      <el-table-column label="操作" fixed="right" align="center" min-width="140px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="showDetail(scope.row.id)"
            v-hasPermi="['business:order:update']"
          >
            查看详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderApi, Order } from '@/api/business/order'
import OrderForm from './OrderForm.vue'
import {VenueApi} from "@/api/business/venue";
import {ServiceClassApi} from "@/api/business/serviceclass";
import {handleTree} from "@/utils/tree";
import {ContentWrap} from "@/components/ContentWrap";

/** 订单 列表 */
defineOptions({ name: 'BizOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Order[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  orderNo: undefined,
  coachId: undefined,
  coachName: undefined,
  coachMobile: undefined,
  serviceIds: undefined,
  venueId: undefined,
  nickname: undefined,
  mobile: undefined,
  orderTime: [],
  paymentStatus: undefined,
  paymentTime: [],
  cancelType: undefined,
  status: undefined,
  refundStatus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const router = useRouter() // 路由

const showDetail = async (id:number) => {
  router.push({
    name: 'OrderDetail',
    query: { id }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除订单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await OrderApi.deleteOrderList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Order[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, '订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const venues = ref([])
const getVenueAll = async () => {
  venues.value = await VenueApi.getVenueAll()
}

const serviceClassTree = ref([])
const getServiceClassAll = async () => {
  serviceClassTree.value = []
  const data = await ServiceClassApi.getServiceClassAll()
  serviceClassTree.value = handleTree(data, 'id', 'parentId')
}

/** 初始化 **/
onMounted(() => {
  getList()
  getVenueAll()
  getServiceClassAll()
})
</script>
